package com.lepu.app.fun.index.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.app.utils.LoginUtil;
import com.app.utils.Setting;
import com.app.utils.UmengEvent;
import com.core.lib.application.BaseFragment;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.Observer;
import com.core.lib.utils.main.AppManager;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UmengHelper;
import com.core.lib.utils.photo.UniversalImageLoadTool;
import com.core.lib.widget.GoogleRefreshLayout;
import com.core.lib.widget.GoogleRefreshLayout.OnLoadListener;

import com.lepu.app.fun.bbs.bean.BeanBbs;
import com.lepu.app.fun.index.adapter.IndexVideoAdapter;
import com.lepu.app.fun.index.bean.BeanIndexNew;
import com.lepu.app.fun.my.MyArticleInfoActivity;
import com.lepu.app.fun.my.bean.BeanMyArticle;
import com.lepu.pasm.R;

@SuppressLint("InflateParams")
public class FragmentVideo extends BaseFragment implements AsyncRequest,
        OnRefreshListener, OnLoadListener, Observer {

    private static final String REQUEST_DATA = "request_data";
    private static final String REQUEST_DATA_MORE = "request_data_more";

    private static final int MSG_DATA_SUCCESS = 10;
    private static final int MSG_DATA_FAIL = 11;
    private static final int MSG_DATA_MORE_SUCCESS = 12;
    private static final int MSG_DATA_MORE_FAIL = 13;


    // ========================================================================
    private GoogleRefreshLayout mGoogleRefreshLayout = null;
    private ListView mDataListView = null;

    private IndexVideoAdapter mDataAdapter = null;
    private ArrayList<BeanMyArticle> mDataArrayList = null;

    private int mCurrentPage = 1;
    private boolean mInitDataSuccess = false;

    private View mMainView = null;

    public String mArticleTag = "";
    private int mType = 0;

    private View mHeadView = null;
    private FrameLayout mHeadLayout = null;
    private ImageView mHeadImageView = null;
    private TextView mHeadTextView = null;

    @SuppressLint("InflateParams")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mMainView = LayoutInflater.from(getActivity()).inflate(R.layout.video_fragment, null, false);
        init();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        ViewGroup p = (ViewGroup) mMainView.getParent();
        if (p != null) {
            p.removeAllViewsInLayout();
        }
        return mMainView;
    }

    @Override
    public void onResume() {
        super.onResume();

        if (!TextUtils.isEmpty(mArticleTag)) {
            if (mType == 0) {
                UmengHelper.onResume(getActivity(), UmengEvent.page_shouye_shipinjicui_yongaoguanli);
            } else if (mType == 1) {
                UmengHelper.onResume(getActivity(), UmengEvent.page_shouye_shipinjicui_dongmanxilie);
            } else if (mType == 2) {
                UmengHelper.onResume(getActivity(), UmengEvent.page_shouye_shipinjicui_baikejiangzuo);
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();

        if (!TextUtils.isEmpty(mArticleTag)) {
            if (mType == 0) {
                UmengHelper.onPause(getActivity(), UmengEvent.page_shouye_shipinjicui_yongaoguanli);
            } else if (mType == 1) {
                UmengHelper.onPause(getActivity(), UmengEvent.page_shouye_shipinjicui_dongmanxilie);
            } else if (mType == 2) {
                UmengHelper.onPause(getActivity(), UmengEvent.page_shouye_shipinjicui_baikejiangzuo);
            }
        }

    }

    @Override
    public void onDestroy() {

        super.onDestroy();
        mInitDataSuccess = false;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (isVisibleToUser) {
            if (!mInitDataSuccess) {

                //一个activity加入多个fragment，有些手机不能自动加载更多，需要调一下这个方法，就可以了！！！
                mHandler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        mGoogleRefreshLayout.setRefreshing(true);  //直接调用是没有用的
                    }
                }, 100);
                request(false);
            }
        }
    }

    private void showHideNoDataLayout(boolean isShow) {
        LinearLayout noDataLayout = (LinearLayout) mMainView.findViewById(R.id.noDataLayout);
        if (noDataLayout != null) {
            if (isShow) {
                noDataLayout.setVisibility(View.VISIBLE);
            } else {
                noDataLayout.setVisibility(View.GONE);
            }
        }
    }

    @SuppressWarnings("deprecation")
    @SuppressLint({"ResourceAsColor", "DefaultLocale"})
    private void init() {
        mDataListView = (ListView) mMainView.findViewById(R.id.dataListView);
        mGoogleRefreshLayout = (GoogleRefreshLayout) mMainView.findViewById(R.id.swipeLayout);
        mGoogleRefreshLayout.setOnRefreshListener(this);
        mGoogleRefreshLayout.setOnLoadListener(this);
        mGoogleRefreshLayout.setColorScheme(R.color.color_listview_refresh_1,
                R.color.color_listview_refresh_2,
                R.color.color_listview_refresh_3,
                R.color.color_listview_refresh_4);


        Bundle data = getArguments();

        if (data != null) {
            mArticleTag = data.getString("ArticleTag");
            mType = data.getInt("Type");
        }

        mHeadView = LayoutInflater.from(getActivity()).inflate(R.layout.index_video_head_view, null);
        mHeadLayout = (FrameLayout) mHeadView.findViewById(R.id.headLayout);
        mHeadImageView = (ImageView) mHeadView.findViewById(R.id.imageView);
        mHeadTextView = (TextView) mHeadView.findViewById(R.id.textView);

        WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params.width = width;
        params.height = width * 9 / 16;// width * 9 / 16;
        mHeadImageView.setLayoutParams(params);

        mDataArrayList = new ArrayList<BeanMyArticle>();
        mDataListView.addHeaderView(mHeadView);
        mDataAdapter = new IndexVideoAdapter(getActivity(), mDataArrayList);
        mDataListView.setAdapter(mDataAdapter);
    }

    // 请求数据
    public void request(boolean isMore) {

        String request = "";
        int page = 1;
        if (isMore) {
            request = REQUEST_DATA_MORE;
            page = (mCurrentPage + 1);
        } else {
            request = REQUEST_DATA;
            mCurrentPage = page;
        }

        String url = Setting.getVideoListUrl();

        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject params = new JSONObject();
        try {
            params.put("DeviceID", Setting.DEVICEID);
            params.put("ApplicationID", Setting.APPLICATIONID);

            params.put("UserID", LoginUtil.getUserId());
            params.put("LoginToken", LoginUtil.getLoginToken());

            params.put("BranchID", Setting.getBranchID(getActivity()));
            params.put("DeviceSN", AppManager.getDeviceUniqueId(getActivity()));

            params.put("ArticleTag", mArticleTag);

            params.put("PageIndex", page);
            params.put("PageSize", Setting.PAGE_SIZE);
            params.put("SortDirection", "DESC");

            int version = AppManager.getVersionCode(getActivity(), getActivity().getPackageName());
            params.put("ClientVersion", String.valueOf(version));


        } catch (Exception e) {
        }
        map.put("ht", params);
        ApiClient.http_post(url, map, null, this, request, true, false, true);
    }

    @SuppressLint("HandlerLeak")
    @SuppressWarnings("unchecked")

    public Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {

            if (getActivity() == null) {
                return;
            }

            switch (msg.what) {
                case MSG_DATA_SUCCESS:

                    String data = (String) msg.obj;
                    ArrayList<BeanMyArticle> dataList = BeanMyArticle.parseListInfo(data);
                    final ArrayList<BeanMyArticle> bannerList = BeanMyArticle.parseBannerListInfo(data);

                    if (dataList != null && dataList.size() > 0) {
                        showHideNoDataLayout(false);
                        mDataArrayList.clear();
                        mDataArrayList.addAll(dataList);

                        mDataListView.removeHeaderView(mHeadView);
                        //更新banner
                        if (bannerList != null && bannerList.size() > 0) {
                            mHeadLayout.setVisibility(View.VISIBLE);
                            UniversalImageLoadTool.disPlay(bannerList.get(0).Cover, mHeadImageView, R.drawable.default_icon_small);
                            mHeadTextView.setText(bannerList.get(0).ArticleTitle);

                            mHeadLayout.setOnClickListener(new OnClickListener() {

                                @Override
                                public void onClick(View arg0) {
                                    Intent intent = new Intent(getActivity(), MyArticleInfoActivity.class);
                                    intent.putExtra("ArticleID", bannerList.get(0).ArticleID);
                                    ((BaseFragmentActivity) getActivity()).startActivity(intent, true);

                                    BeanIndexNew.insertTargetId(bannerList.get(0).ArticleID);
                                }
                            });
                        } else {
                            mHeadLayout.setVisibility(View.GONE);
                        }
                        mDataListView.addHeaderView(mHeadView);

                        mDataAdapter = new IndexVideoAdapter(getActivity(), mDataArrayList);
                        mDataListView.setAdapter(mDataAdapter);

                        mInitDataSuccess = true;
                    } else {
                        showHideNoDataLayout(true);

                        if (mDataArrayList != null && mDataArrayList.size() > 0) {
                            mDataArrayList.clear();
                        }
                    }

                    // 更新完后调用该方法结束刷新
                    mHandler.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            mGoogleRefreshLayout.setRefreshing(false);  //直接调用是没有用的
                        }
                    }, 100);

                    if (mDataArrayList != null && mDataArrayList.size() > 0) {
                        if (mDataArrayList.size() < Setting.PAGE_SIZE) {
                            mGoogleRefreshLayout.setLoadMoreFinish(true);
                        }
                    } else {
                        mGoogleRefreshLayout.setLoadMoreFinish(true);
                    }
                    break;
                case MSG_DATA_FAIL:
                    // 更新完后调用该方法结束刷新
                    mHandler.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            mGoogleRefreshLayout.setRefreshing(false);  //直接调用是没有用的
                        }
                    }, 100);
                    showHideNoDataLayout(true);
                    break;
                case MSG_DATA_MORE_SUCCESS:

                    ArrayList<BeanBbs> dataMoreList = (ArrayList<BeanBbs>) msg.obj;

                    if (dataMoreList != null && dataMoreList.size() > 0) {

                        mDataAdapter.notifyDataSetChanged();

                        // 加载更多数据成功，page ++
                        mCurrentPage++;
                    } else {
                       // UIHelper.showToast(getActivity(), R.string.no_data_more);
                        mGoogleRefreshLayout.setLoadMoreFinish(true);
                    }

                    // 加载完后调用该方法
                    mGoogleRefreshLayout.setLoading(false);
                    break;
                case MSG_DATA_MORE_FAIL:

                    // 加载完后调用该方法
                    mGoogleRefreshLayout.setLoading(false);
                    break;

                default:
                    break;
            }
        }

        ;
    };

    @Override
    public void onLoad() {
        request(true);
    }

    @Override
    public void onRefresh() {
        request(false);
    }

    @Override
    public void RequestComplete(Object object, Object data) {
        if (object.equals(REQUEST_DATA)) {

            Message msg = mHandler.obtainMessage();
            msg.what = MSG_DATA_SUCCESS;
            msg.obj = (String) data;
            mHandler.sendMessage(msg);
        } else if (object.equals(REQUEST_DATA_MORE)) {
            ArrayList<BeanMyArticle> dataMoreArraylist = BeanMyArticle.parseListInfo((String) data);

            if (dataMoreArraylist != null && dataMoreArraylist.size() > 0) {
                mDataArrayList.addAll(dataMoreArraylist);
            }

            Message msg = mHandler.obtainMessage();
            msg.what = MSG_DATA_MORE_SUCCESS;
            msg.obj = dataMoreArraylist;
            mHandler.sendMessage(msg);
        }
    }

    @Override
    public void RequestError(Object object, int errorId, String errorMessage) {
        if (object.equals(REQUEST_DATA)) {
            mHandler.sendEmptyMessage(MSG_DATA_FAIL);
        } else if (object.equals(REQUEST_DATA_MORE)) {
            mHandler.sendEmptyMessage(MSG_DATA_MORE_FAIL);
        }
    }

    @Override
    public void notify(String arg0, Object arg1, Object arg2) {
        request(false);
    }

}
